// JavaScript Document
//Global variables
var OOSHTML;
	
$(document).ready(function() {
    $("a[rel^='productPhoto']").prettyPhoto();

    var itemsperpage = $("#productThumbImagePageItems").val();

    $('.sliderContainervertical').each(function () {

        var list_obj = $(this).find('.slidervertical ul');
        var next_obj = $(this).find('.next-slide');
        var prev_obj = $(this).find('.prev-slide');
        var listitems = list_obj.find('li').length;
        var itemheight = list_obj.find('li').height();
        var pageheight = itemsperpage * itemheight;
        var pagenums = Math.ceil(parseInt(listitems / itemsperpage));
        var scrollHeight = -1 * (listitems * itemheight);
        list_obj.height(listitems * itemheight);

        if (listitems <= itemsperpage) {
            prev_obj.addClass('disabled');
            next_obj.addClass('disabled');
        }
        else {
            prev_obj.click(function () {
                if (!$(this).hasClass('disabled')) {
                    var currentScrollTop = parseInt(list_obj.css('top'));
                    currentScrollTop = currentScrollTop + pageheight;
                    if (currentScrollTop == 0) {
                        prev_obj.addClass('disabled');
                    }
                    next_obj.removeClass('disabled');
                    list_obj.animate({ 'top': currentScrollTop + 'px', 'easing': 'swing' });
                }
            });

            next_obj.click(function () {
                if (!$(this).hasClass('disabled')) {
                    var currentScrollTop = parseInt(list_obj.css('top'));
                    currentScrollTop = currentScrollTop - pageheight;
                    if (currentScrollTop - pageheight <= scrollHeight) {
                        next_obj.addClass('disabled');
                    }
                    prev_obj.removeClass('disabled');
                    list_obj.animate({ 'top': currentScrollTop + 'px', 'easing': 'swing' });
                }
            });
        }
    });

    $('.sliderContainerhorizontal').each(function () {

        var list_obj = $(this).find('.sliderhorizontal ul');
        var next_obj = $(this).find('.next-slide');
        var prev_obj = $(this).find('.prev-slide');
        var listitems = list_obj.find('li').length;
        var itemwidth = list_obj.find('li').width();
        var pagewidth = itemsperpage * itemwidth;
        var pagenums = Math.ceil(parseInt(listitems / itemsperpage));
        var scrollWidth = -1 * (listitems * itemwidth);
        list_obj.width(listitems * itemwidth);

        if (listitems <= itemsperpage) {
            prev_obj.addClass('disabled');
            next_obj.addClass('disabled');
        }
        else{
            prev_obj.click(function () {
                if (!$(this).hasClass('disabled'))
                {
                    var currentScrollLeft = parseInt(list_obj.css('left'));
                    currentScrollLeft = currentScrollLeft + pagewidth;
                    if (currentScrollLeft == 0) {
                        prev_obj.addClass('disabled');
                    }
                    next_obj.removeClass('disabled');
                    list_obj.animate({ 'left': currentScrollLeft + 'px', 'easing':'swing'});
                }
            });

            next_obj.click(function () {
                if (!$(this).hasClass('disabled'))
                {
                    var currentScrollLeft = parseInt(list_obj.css('left'));
                    currentScrollLeft = currentScrollLeft - pagewidth;
                    if (currentScrollLeft - pagewidth <= scrollWidth) {
                        next_obj.addClass('disabled');
                    }
                    prev_obj.removeClass('disabled');
                    list_obj.animate({ 'left': currentScrollLeft + 'px','easing':'swing'});
                }
            });
        }
    });
});
  

//functions
function getCheckedValue(radioObj) {
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
            return radioObj.value;
        else
            return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

//Matrix Change Options
function renderPageValues(data, sInstanceID, index, selectedMatrixValue) {
    var o = jQuery.parseJSON(data);
    var productid = $("#id" + sInstanceID).val();
    var doChanges = true;
    
    if ($("#allowOOSPurchase" + sInstanceID).val() != 'true') {
        if (parseInt(o.qis) <= 0) {
            doChanges = false;
        }
        else {
            $("#maxQty" + sInstanceID).val(o.qis);
            updateQty(o.qis, sInstanceID);
            $("#qtyHolder" + sInstanceID).show();
        }
    }

    if (doChanges) {
        $("#canAddToBasket" + sInstanceID).val("true");
        $("#pinc" + sInstanceID).html(o.priceIncVAT);
        $("#pexc" + sInstanceID).html(o.priceExcVAT);
        $("#wpexc" + sInstanceID).html(o.wasPriceExcVAT);
        $("#wpinc" + sInstanceID).html(o.wasPriceIncVAT);
        $("#sinc" + sInstanceID).html(o.saveIncVAT);
        $("#sexc" + sInstanceID).html(o.saveExcVAT);
        $("#psm" + sInstanceID).html(o.stock);

        if (parseInt(o.qib) > 0) {
            $("#qib" + sInstanceID).html(o.qib);
            $("#qibc" + sInstanceID).show();
        }
        else {
            $("#qibc" + sInstanceID).hide();
        }

        if (parseInt(o.qis) <= 0) {
            $("#productstamp" + sInstanceID).removeClass('StockClassIn').addClass('StockClassOut');
            $("#desc").removeClass('StockClassIn').addClass('StockClassOut');
            $("#psm" + sInstanceID).removeClass('ins oos').addClass('oos');
            $("#stocknotify").attr("href", o.emailWhenBackInStock).show();
        }
        else {
            $("#productstamp" + sInstanceID).removeClass('StockClassOut').addClass('StockClassIn');
            $("#desc").removeClass('StockClassOut').addClass('StockClassIn');
            $("#psm" + sInstanceID).removeClass('ins oos').addClass('ins');
            $("#stocknotify").hide();
        }

        //if the item is out of stock hide the add to basket button and show the stock notification form
        if ($("#allowOOSPurchase" + sInstanceID).val() != 'true') {
            if (parseInt(o.qis) <= 0) {
                $("#buynowcontainer").hide();
                $("#qtyHolder" + sInstanceID).hide();

                if ($('allowOOSEmail').val() == 'true') {
                    $("#StockNotifyLink").show();
                }
            } else {
                $("#buynowcontainer").show();
                $("#StockNotifyLink").hide();
                $("#maxQty" + sInstanceID).val(o.qis);
                updateQty(o.qis, sInstanceID);
                $("#qtyHolder" + sInstanceID).show();
            }
        }
        var thisRenderType = $("#type" + index).val();
    }
    else
    {
        $("#canAddToBasket" + sInstanceID).val("false");
    }
    renderVisuals(thisRenderType, index, selectedMatrixValue);
    renderImages(o, sInstanceID);
}

function renderImages(o, sInstanceID) {
    var isProductStamp = $("#isProductStamp" + sInstanceID).val();

    if (isProductStamp == 'true')
    {
        $("#stampImage" + sInstanceID).empty();
        $("#stampImage" + sInstanceID).append(o.mainImages);
    }
    else
    {
        $("#productImageList" + sInstanceID).empty();
        $("#productThumbGalleryList" + sInstanceID).empty();

        $("#productImageList" + sInstanceID).append(o.mainImages);
        $("#productThumbGalleryList" + sInstanceID).append(o.imageGallery);
    }
}

function productImageReplace(index) {

    var li = $("#" + index);
    if (li) {
        $(li).parent().prepend(li);
    }
}

function addElements(idAdd, options, swatch, renderType)
{
    if (swatch != "") 
    {
        $('#MatrixSwatch' + idAdd).empty();
        $('#MatrixSwatch' + idAdd).append(swatchBits[i]);
        $("#MatrixSwatch" + idAdd + " > a").removeClass("selected");
    }

    switch (renderType) {
        case "N": case "CD": case "ID":
            //'default drop down
            $('#Matrix' + idAdd).empty();
            $('#Matrix' + idAdd).append(options);
            break;
        case "R": case "IR": case "CR":
            //radiobutton
            $('#Matrix' + idAdd)[0].options.length = 0;
            $('#Matrix' + idAdd).append(options);
            break;
        case "T": case "CT": case "IT":
            //text in div
            $("#Matrix" + idAdd + " > div").remove();
            $('#Matrix' + idAdd).append(options);
            break;
        default:
            //alert(renderType + ' not found');
            break;
    }
    $("#value-" + idAdd).val("");
}

function removeElements(idAdd, renderType)
{
    $("#value" + idAdd).val("");

    switch (renderType) {
        case "N": case "CD": case "ID":
            //'default drop down
            $("#Matrix" + idAdd).empty();
            break;
        case "R": case "IR": case "CR":
            //radiobutton
            $('#Matrix' + idAdd)[0].options.length = 0;
            break;
        case "T": case "CT": case "IT":
            //text in div
            $("#Matrix" + idAdd + " > div").remove();
            break;
        default:
            //alert(renderType + ' not found');
            break;
    }
    $("#MatrixSwatch" + idAdd + " > a").remove();
}

function renderMatrix(data, axisCount, GroupIndex, sInstanceID, index, selectedMatrixValue, renderType)
{
    var splitbits = data.split("~");
    var optionbits = splitbits[0];
    var swatchBits = ""; if (splitbits[1]) { swatchBits = splitbits[1]; }
    var requiredAxisNumber = parseInt(GroupIndex) + 1
    var currentIndex = parseInt(GroupIndex) + 1;

    var idAdd = "";

    for (var i = parseInt(currentIndex) ; i <= parseInt(axisCount) ; i++) {

        idAdd = String(i) + String(sInstanceID)

        var thisRenderType = $("#type" + idAdd).val();
        if (i == parseInt(requiredAxisNumber)) {
            addElements(idAdd, optionbits, swatchBits, thisRenderType);
        }
        else if (i > parseInt(requiredAxisNumber)) 
        {
            removeElements(idAdd, thisRenderType);
        }
    }
    renderVisuals(renderType, idAdd, selectedMatrixValue);
}

function renderVisuals(renderType, idAdd, selectedMatrixValue)
{
    switch (renderType) {
        case "N": case "CD": case "ID":
            //'default drop down
            $("#Matrix" + idAdd).val(selectedMatrixValue);
            break;
        case "R": case "IR": case "CR":
            //radiobutton
            setCheckedValue($('input[name="Matrix' + idAdd + '"]'), selectedMatrixValue);
            break;
        case "T": case "CT": case "IT":
            //text in div
            $("#Matrix" + idAdd + " > div").removeClass("selected");
            if (typeof (selectedMatrixValue) != "undefined") {
                $("#Matrix" + idAdd + "-" + selectedMatrixValue).addClass("selected");
            }
            break;
        default:
            break;
    }

    $("#MatrixSwatch" + idAdd + " > a").removeClass("selected");
    if (typeof (selectedMatrixValue) != "undefined") {
        $("#MatrixSwatch" + idAdd + "-" + selectedMatrixValue).addClass("selected");
    }
}

function selectionsChanged(index, mdata) {
    var sInstanceID = "";
    var iInstanceID = "";
    var GroupIndex = 0;
    
    var indexbits = index.split("_")
    iInstanceID = indexbits[1];
    sInstanceID = "_" + indexbits[1];
    GroupIndex = indexbits[0];
  
    var url = "/ajax/matrix";
    var productid = $("#id" + sInstanceID).val();

    var selectedMatrixValue = ''
    if (mdata != '') 
    {
        selectedMatrixValue = mdata;
    }
    else 
    {
        selectedMatrixValue = $("#Matrix" + index).val();
    }

    $("#value" + index).val(selectedMatrixValue);
    var type = $("#type" + index).val();

    var axisCount = $("#AxisCount" + sInstanceID).val();
    var postdata;
    postdata = "stockcode=" + productid;
    postdata += "&AxisCount=" + axisCount;
    postdata += "&GroupIndex=" + GroupIndex;
    postdata += "&InstanceID=" + iInstanceID;
    postdata += "&AxisValue=" + selectedMatrixValue;

    for (var i = 1; i <= axisCount; i++) 
    {
        if (typeof ($("#Matrix" + i + sInstanceID).val()) != 'undefined') 
        {
            postdata += "&AxisID" + i + "=" + $("#axis" + i + sInstanceID).val();
            postdata += "&AxisName" + i + "=" + $("#name" + i + sInstanceID).val();
            postdata += "&AxisType" + i + "=" + $("#type" + i + sInstanceID).val();
            postdata += "&AxisValue" + i + "=" + $("#value" + i + sInstanceID).val();
        }
    }

    if (parseInt(GroupIndex) != parseInt(axisCount)) 
    {
        if (selectedMatrixValue > 0) { //not blank selected
            postdata += "&EventType=ChangeAxis";
            postdata = encodeURI(postdata);

            $.ajax({
                dataType: "json",
                type: "POST",
                url: url,
                async: false,
                data: postdata,
                success: function (data) {
                    renderMatrix(data, axisCount, GroupIndex, sInstanceID, index, selectedMatrixValue, type);
                }
            });
        }
        else
        {
            $("#value" + index).val("");
            $("#canAddToBasket" + sInstanceID).val("false");
            var idAdd = "";
            var currentIndex = parseInt(GroupIndex) + 1;
            for (var i = parseInt(currentIndex) ; i <= parseInt(axisCount) ; i++) {
                 idAdd = String(i) + String(sInstanceID)
                 var thisRenderType = $("#type" + idAdd).val();
                 removeElements(idAdd, thisRenderType);
            }
        }
    }
    else 
    {
        if (selectedMatrixValue > 0) { //not blank selected
            postdata += "&EventType=ChangeLastAxis";
            postdata += "&isProductStamp=" + $("#isProductStamp" + sInstanceID).val();
            postdata += "&overrideCustomerGridList=" + $("#overrideCustomerGridList" + sInstanceID).val();
            postdata = encodeURI(postdata);

            $.ajax({
                dataType: "json",
                type: "POST",
                url: url,
                async: false,
                data: postdata,
                success: function (data) {
                    renderPageValues(data, sInstanceID, index, selectedMatrixValue);
                }
            });
        }
        else
        {
            $("#value" + index).val("");
            $("#canAddToBasket" + sInstanceID).val("false");
        }
    }
}

//Quantity Selector Functions
function minusone(id) {

    var minQty = parseInt($("#Qty" + id).attr('data-min-qty'));
    var minOrderQty = parseInt($("#Qty" + id).attr('data-minorder-qty')) || 1;
    var QtyMultiple = parseInt($("#Qty" + id).attr('data-qty-multiple')) || 1;
    var GroupMinOrderQty = parseInt($("#Qty" + id).attr('data-group-minorder-qty')) || 1;
    var GroupQtyMultiple = parseInt($("#Qty" + id).attr('data-group-qty-multiple')) || 1;
    var groupID = $("#Qty" + id).attr('data-groupid');
    var isGroupMinQty = false;
    var productName = $('#pageH1').find('h1').html() || "Minimum order requirement";
    var showLowQtyMsg = false;
    if ($("#allowZeroQty").length > 0) {
        minQty = 0;
    }
    var Qty = $("#Qty" + id).val();
    var OQty = Qty;

    if (Qty == "") { Qty = getMyQty(id); }

    // if a line quantity multiple has not been set then use the group quantity multiple
    if (GroupQtyMultiple > 1 && QtyMultiple <= 1) { QtyMultiple = GroupQtyMultiple; isGroupMinQty = true; }

    Qty = parseInt(Qty) - QtyMultiple;

    if (parseInt(Qty) < parseInt(minQty)) { Qty = minQty; showLowQtyMsg = true }

    if (groupID == '' || !isGroupMinQty) { if (minOrderQty > 1 && Qty < minOrderQty) { Qty = minOrderQty; showLowQtyMsg = true; } }
    if (QtyMultiple > 1 && Qty % QtyMultiple > 0) { Qty = Qty.roundUpTo(QtyMultiple); }

    $("#Qty" + id).val(Qty);
    setMyQty(id, Qty);

    if (showLowQtyMsg == true) { showTinyBoxMsg('<h3>' + productName + '</h3><br><b>Please note:</b><br />The minimum order quantity for this product is <b>' + Qty + '</b>', 300, 100, 80, true, 0); }

    if (id != '' && OQty != Qty) {
        try {
            document.forms.frm_Basket.action.value = "change";
            $("#checkoutClicked").val('false');
            document.forms.frm_Basket.submit();
        } catch (err) { }

    }
}

function addone(id) {

    var maxQty = parseInt($("#Qty" + id).attr('data-max-qty'));
    var minOrderQty = parseInt($("#Qty" + id).attr('data-minorder-qty')) || 1;
    var QtyMultiple = parseInt($("#Qty" + id).attr('data-qty-multiple')) || 1;
    var GroupMinOrderQty = parseInt($("#Qty" + id).attr('data-group-minorder-qty')) || 1;
    var GroupQtyMultiple = parseInt($("#Qty" + id).attr('data-group-qty-multiple')) || 1;
    var groupID = $("#Qty" + id).attr('data-groupid');
    var Qty = $("#Qty" + id).val();
    var OQty = Qty;

    if (Qty == "") { Qty = getMyQty(id) }

    // if a line quantity multiple has not been set then use the group quantity multiple
    if (GroupQtyMultiple > 1 && QtyMultiple <= 1) { QtyMultiple = GroupQtyMultiple; }

    Qty = parseInt(Qty) + 1;
    if (parseInt(Qty) > parseInt(maxQty)) { Qty = maxQty; }

    if (minOrderQty > 1 && Qty < minOrderQty) { Qty = minOrderQty; }
    if (QtyMultiple > 1 && Qty % QtyMultiple > 0) { Qty = Qty.roundUpTo(QtyMultiple); }

    if (groupID != '') {
        //	if (GroupMinOrderQty > 1) {

        //	}
    }

    $("#Qty" + id).val(Qty);
    setMyQty(id, Qty);

    if (id != '' && OQty != Qty) {
        try {
            document.forms.frm_Basket.action.value = "change";
            $("#checkoutClicked").val('false');
            document.forms.frm_Basket.submit();
        } catch (err) { }
    }
}

function setMyQty(id, val) {
    //set qty only if it is not empty
    if ($.trim(val) != '' && !isNaN(val)) {
        $("#Qty" + id).attr('data-my-qty', val);
    }
}

function getMyQty(id) {

    var tmp = $("#Qty" + id).attr('data-my-qty');
    if (!tmp || $.trim(tmp) == '' || isNaN(tmp)) { tmp = 0; }
    return tmp;
}

function checkQty(id) {
    var i;
    var s = $("#Qty" + id).val();
    var bag = '1234567890';
    var Qty = "";
    var minQty = parseInt($("#Qty" + id).attr('data-min-qty'));
    var maxQty = parseInt($("#Qty" + id).attr('data-max-qty'));
    var minOrderQty = parseInt($("#Qty" + id).attr('data-minorder-qty')) || 1;
    var QtyMultiple = parseInt($("#Qty" + id).attr('data-qty-multiple')) || 1;
    var GroupMinOrderQty = parseInt($("#Qty" + id).attr('data-group-minorder-qty')) || 1;
    var GroupQtyMultiple = parseInt($("#Qty" + id).attr('data-group-qty-multiple')) || 1;
    var groupID = $("#Qty" + id).attr('data-groupid');
    var productName = $('#pageH1').find('h1').html() || "Minimum order requirement";
    var showLowQtyMsg = false;
    var showMultipleMsg = false;

    if ($("#allowZeroQty").length > 0) {
        minQty = 0;
    }

    // if a line quantity multiple has not been set then use the group quantity multiple
    if (GroupQtyMultiple > 1 && QtyMultiple <= 1) { QtyMultiple = GroupQtyMultiple; }

    for (i = 0; i < s.length; i++) {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) Qty += c;
    }

    if (Qty == "" || isNaN(Qty)) { Qty = getMyQty(id) }

    Qty = parseInt(Qty);

    if (Qty < parseInt(minQty)) { Qty = minQty; }
    if (Qty > parseInt(maxQty)) { Qty = maxQty; showLowQtyMsg = true; }

    if (minOrderQty > 1 && Qty < minOrderQty) { Qty = minOrderQty; showLowQtyMsg = true; }
    if (QtyMultiple > 1 && Qty % QtyMultiple > 0) {
        if (minOrderQty < Qty.roundUpTo(QtyMultiple)) { showLowQtyMsg = true; };
        Qty = Qty.roundUpTo(QtyMultiple); showMultipleMsg = true;
    }

    $("#Qty" + id).val(Qty);

    if (showLowQtyMsg && showMultipleMsg) { showTinyBoxMsg('<h3>' + productName + '</h3><br><b>Please note:</b><br />The minimum order quantity for this product is <b>' + minOrderQty + '</b> and must be ordered in quantities of <b>' + QtyMultiple + '</b>', 300, 120, 80, true, 0); }
    else if (showLowQtyMsg) { showTinyBoxMsg('<h3>' + productName + '</h3><br><b>Please note:</b><br />The minimum order quantity for this product is <b>' + minOrderQty + '</b>', 300, 100, 80, true, 0); }
    else if (showMultipleMsg) { showTinyBoxMsg('<h3>' + productName + '</h3><br><b>Please note:</b><br />This product must be ordered in multiples of <b>' + QtyMultiple + '</b>', 300, 100, 80, true, 0); }

}
function checkQtyChange(id) {
    if (id != '') {
        var Qty = $("#Qty" + id).val();
        var OQty = $("#Qty" + id).attr('data-old-qty');

        if (OQty != Qty) {
            try {
                document.forms.frm_Basket.action.value = "change";
                $("#checkoutClicked").val('false');
                document.forms.frm_Basket.submit();
            } catch (err) { }
        }
    }
}